//
//  BPCustomView.m
//  BeautyPicture
//
//  Created by 沈振邦 on 15/9/20.
//  Copyright (c) 2015年 szb. All rights reserved.
//

#import "BPCustomView.h"
#import "BPImageTool.h"
#import "UIImageView+WebCache.h"
#import "MBProgressHUD+MJ.h"

@implementation BPCustomView

- (id)init
{
    self = [super init];
    if (self) {
        [self setUpCustomView];
        
        
        NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
        //添加当前类对象为一个观察者，name和object设置为nil，表示接收一切通知
        [center addObserver:self selector:@selector(notice:) name:@"123" object:nil];
        
    }
    return self;
}

// 通知(加载页面)
- (void)notice:(NSNotification *)tion
{
    // 页面刷新
    self.clipsToBounds = YES;
    self.backgroundColor = [UIColor clearColor];
    self.layer.borderColor = [BPGlobaThemeColor CGColor];

}

- (void)setUpCustomView
{
    
    
    
    // 长按 之后 出现的 框框(粉红色 的)
    self.clipsToBounds = YES;
    self.backgroundColor = [UIColor clearColor];
    self.layer.borderColor = [BPGlobaThemeColor CGColor];
    
    self.showAssetView = [[UIView alloc] init];
    self.showAssetView.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.showAssetView];
    
    self.assetImage = [[UIImageView alloc] init];
    _assetImage.userInteractionEnabled = YES;
    [self.showAssetView addSubview:_assetImage];
    
    //旋转手势
    UIRotationGestureRecognizer *rotateGes = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotateImage:)];
    [_assetImage addGestureRecognizer:rotateGes];
    
    //缩放手势
    UIPinchGestureRecognizer *scaleGes = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scaleImage:)];
    [_assetImage addGestureRecognizer:scaleGes];
    
    //平移手势
    UIPanGestureRecognizer *moveGes = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(moveImage:)];
    [moveGes setMinimumNumberOfTouches:1];
    [moveGes setMaximumNumberOfTouches:1];
    [_assetImage addGestureRecognizer:moveGes];
    
    //添加长按手势
    UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressShowImageToolBar:)];
    longPress.minimumPressDuration = 0.7f;
    [self addGestureRecognizer:longPress];
}

- (void)setUpnopxImageView
{
    
    _imageVBlock = [[UIImageView alloc] initWithFrame:self.bounds];
    _imageVBlock.image = [UIImage imageNamed:@"black"];
    _imageVBlock.alpha = 0.7;
    [self.showAssetView addSubview:_imageVBlock];
    
    _nopxImage = [[UIImageView alloc] initWithFrame:CGRectMake(self.frame.size.width / 2 - 40, self.frame.size.height / 2 - 30, 80, 65)];
    _nopxImage.image = [UIImage imageNamed:@"nomuchpx"];
    [self.imageVBlock addSubview:_nopxImage];
    
    //单击手势
    _tapOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOneShowFilter:)];
    _tapOne.numberOfTapsRequired = 1;
    _tapOne.numberOfTouchesRequired = 1;
    [self addGestureRecognizer:_tapOne];
}

- (void)setUpNopictureImage
{
    _noPicImage = [[UIImageView alloc] initWithFrame:self.bounds];
    _noPicImage.image = [UIImage imageNamed:@"noAssetImage"];
    [self.showAssetView addSubview:_noPicImage];
    
    //单击手势
    _tapOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOneShowFilter:)];
    _tapOne.numberOfTapsRequired = 1;
    _tapOne.numberOfTouchesRequired = 1;
    [self addGestureRecognizer:_tapOne];
}

- (void)removenoPicimage
{
    _noPicImage.image = nil;
    _noPicImage = nil;
    
    [_noPicImage removeFromSuperview];
    [_tapOne removeTarget:self action:@selector(tapOneShowFilter:)];
    [self removeGestureRecognizer:_tapOne];
    _tapOne = nil;
}

- (void)removePXimage
{
    _nopxImage.image = nil;
    _nopxImage = nil;
    
    _imageVBlock.image = nil;
    _imageVBlock = nil;
    
    [_nopxImage removeFromSuperview];
    [_imageVBlock removeFromSuperview];
    
    [_tapOne removeTarget:self action:@selector(tapOneShowFilter:)];
    [self removeGestureRecognizer:_tapOne];
    _tapOne = nil;
}

- (void)addImageModel:(BPProductModel *)imageModel addScale:(CGFloat)scale addAssetarry:(ALAsset *)asset
{
    self.x = imageModel.x * scale;
    self.y = imageModel.y * scale;
    self.width = imageModel.w * scale;
    self.height = imageModel.h * scale;
    self.showAssetView.frame = self.bounds;
    self.assetImage.frame = self.showAssetView.bounds;
   
    //设置编号
    self.tag = imageModel.modelIndex;
    
    //设置照片位置、放大缩小和比例
    if (imageModel.matrix != nil) {
        self.assetImage.transform = CGAffineTransformFromString(imageModel.matrix);
    }
    
    //2.添加一张图片，图片的大小和形状作为显示区域
    NSString *imageUrlStr = [NSString stringWithFormat:@"%@%@%@",pictureUrl,imageModel.mouldPic,ThumbPicture];
    NSURL *imageUrl = [NSURL URLWithString:imageUrlStr];
    __weak typeof(self) weakSelf = self;
    [self.assetImage sd_setImageWithURL:imageUrl placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        //3.获得图片的形状，让显示区域成为图片的形状
        CALayer *BackroundCornerLayer = [CALayer layer];
        BackroundCornerLayer.frame = weakSelf.showAssetView.bounds;
        BackroundCornerLayer.contents = (id)[image CGImage];
        [[weakSelf.showAssetView layer] setMask:BackroundCornerLayer];
        self.assetImage.contentMode = UIViewContentModeScaleAspectFill;
        //将照片转换为图片
        if ([asset isEqual:@"noAsset"]) {
            [self setUpNopictureImage];
        }else{
            CGImageRef ref = [[asset defaultRepresentation] fullScreenImage];
            //CGImageRef ref = [asset aspectRatioThumbnail];
            UIImage *alasset = [[UIImage alloc] initWithCGImage:ref];
            //NSLog(@"%f",_maxScale);
//            NSData *imageData = UIImageJPEGRepresentation(alasset, _maxScale);
            self.assetImage.image = alasset;
            CGSize assetSize = [asset defaultRepresentation].dimensions;
            _assetWith = assetSize.width;
            if (_assetWith * self.maxScale < self.assetImage.width) {
                if (_nopxImage == nil && _imageVBlock == nil) {
                    [self setUpnopxImageView];
                }
            }
        }
    }];
}

- (void)tapOneShowFilter:(UITapGestureRecognizer *)sender
{
    if ([self.delegate respondsToSelector:@selector(backViewTapOne:)]) {
        [self.delegate backViewTapOne:sender];
    }
}


float _lastRotation = 0.0;
- (void)rotateImage:(UIRotationGestureRecognizer *)sender
{
    if ([sender state] == UIGestureRecognizerStateBegan) {
        self.layer.borderWidth = 1.0;
    }
    if([sender state] == UIGestureRecognizerStateEnded) {
        _lastRotation = 0.0;
        self.layer.borderWidth = 0.0;
//        if ([self.delegate respondsToSelector:@selector(rotationAlaset:)]) {
//            [self.delegate rotationAlaset:sender];
//        }
        return;
    }
    CGFloat rotation = -_lastRotation + [sender rotation];
    CGAffineTransform currentTransform = _assetImage.transform;
    CGAffineTransform newTransform = CGAffineTransformRotate(currentTransform,rotation);
    [_assetImage setTransform:newTransform];
    
    _lastRotation = [sender rotation];
}

float _lastScale = 1.0;
- (void)scaleImage:(UIPinchGestureRecognizer *)sender
{
    self.layer.borderWidth = 1.0;
    self.layer.borderColor = [BPGlobaThemeColor CGColor];
    if([sender state] == UIGestureRecognizerStateBegan) {
        self.layer.borderWidth = 1.0;
        _lastScale = 1.0;
        return;
    }
    CGFloat scale = [sender scale]/_lastScale;
    CGAffineTransform currentTransform = _assetImage.transform;
    CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);
    [_assetImage setTransform:newTransform];
    //NSLog(@"%@",NSStringFromCGAffineTransform(self.assetImage.transform));
    //控制放大缩小的限度
    if (_assetImage.width <= _assetWith * _maxScale ) {
        if (_nopxImage != nil && _imageVBlock != nil) {
            [self removePXimage];
        }
    }else{
        if (sender.scale > 1.0) {
            if (_nopxImage == nil && _imageVBlock == nil) {
                [self setUpnopxImageView];
            }
        }
    }
    _lastScale = [sender scale];
    if ([sender state] == UIGestureRecognizerStateEnded) {
        self.layer.borderWidth = 0.0;
//        if ([self.delegate respondsToSelector:@selector(pinchAlaset:)]) {
//            [self.delegate pinchAlaset:sender];
//        }
    }
}

float _lastTransX = 0.0, _lastTransY = 0.0;
- (void)moveImage:(UIPanGestureRecognizer *)sender
{
    CGPoint translatedPoint = [sender translationInView:self];
    if([sender state] == UIGestureRecognizerStateBegan) {
        self.layer.borderWidth = 1.0;
        _lastTransX = 0.0;
        _lastTransY = 0.0;
    }
    
    CGAffineTransform trans = CGAffineTransformMakeTranslation(translatedPoint.x - _lastTransX, translatedPoint.y - _lastTransY);
    
    CGAffineTransform newTransform = CGAffineTransformConcat(_assetImage.transform, trans);
    //NSLog(@"%@",NSStringFromCGAffineTransform(_assetImage.transform));
    [_assetImage setTransform:newTransform];
    _lastTransX = translatedPoint.x;
    _lastTransY = translatedPoint.y;
    if ([sender state] == UIGestureRecognizerStateEnded) {
        self.layer.borderWidth = 0.0;
        if (_assetImage.x > _showAssetView.width - 30.0f) {
            _assetImage.tx = _showAssetView.width - 30.0f;
        }
        if (_assetImage.x < -_assetImage.width + 30.0f) {
            _assetImage.tx = 30.0 - _assetImage.width;
        }
        if (_assetImage.y > _showAssetView.height - 30.0f) {
            _assetImage.ty = _showAssetView.height - 30.0f;
        }
        if (_assetImage.y < 30.0f - _showAssetView.height) {
            _assetImage.ty = 30.0f - _showAssetView.height;
        }
    }
}

- (void)longPressShowImageToolBar:(UILongPressGestureRecognizer *)sender
{
    if ([sender state] == UIGestureRecognizerStateBegan){
        if ([self.delegate respondsToSelector:@selector(backViewPressLong:)]) {
           [self.delegate backViewPressLong:sender];
        }
    }
}

//重置照片位置
- (void)reset
{
    self.assetImage.transform = CGAffineTransformIdentity;
}

////
//- (UIImage *)setUpFilterWithFilterNO:(NSInteger)filterNO addImage:(ALAsset *)orgImage
//{
//    
//    if (filterNO == 0) {
//        
//        CGImageRef ref = [[orgImage defaultRepresentation]fullScreenImage];
//        UIImage *alasset = [[UIImage alloc] initWithCGImage:ref];
//        return alasset;
//        
//    }else if (orgImage != nil && filterNO != 0) {
//        
//        CGImageRef ref = [[orgImage defaultRepresentation]fullScreenImage];
//   
//        CIImage *beginImage = [CIImage imageWithCGImage:ref];
//        
//        CIContext *context = [CIContext contextWithOptions:nil];
//        
//        CIFilter *filter = [self makeFilter:filterNO addImage:beginImage];
//        
//        CIImage *outputImage = [filter outputImage];
//        
//        // 2
//        CGImageRef cgimg = [context createCGImage:outputImage fromRect:[outputImage extent]];
//        
//        // 3
//        UIImage *newImage = [UIImage imageWithCGImage:cgimg];
//        
//        CGImageRelease(cgimg);
//        
//        return newImage;
//    }else{
//        return nil;
//    }
//    
//}
////滤镜处理
//- (CIFilter *)makeFilter:(NSInteger)filterNO addImage:(CIImage *)beginImage
//{
//    CIFilter *filter = [[CIFilter alloc] init];
//    switch (filterNO) {
//        case 1:
//            filter = [CIFilter filterWithName:@"CISepiaTone" keysAndValues:kCIInputImageKey, beginImage,@"inputIntensity",@0.8,nil];
//            break;
//        case 2:
//            filter = [CIFilter filterWithName:@"CIHueAdjust" keysAndValues:kCIInputImageKey, beginImage,@"inputAngle",@0.8,nil];
//            break;
//            
//        default:
//            break;
//    }
//    return filter;
//}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
